package com.exsun.gateway.jt809.slave.handler;

import com.exsun.gateway.jt809.codec.MsgEncoder;
import com.exsun.gateway.jt809.codec.MsgDecoder;
import com.exsun.gateway.jt809.common.LinkType;
import com.exsun.gateway.jt809.config.NettyClientConfig;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
@Component
public class JT809ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
	@Autowired
	JT809ServerHandler jt809ServerHandler;
	@Autowired
	public NettyClientConfig nettyClientConfig;

	public static final LinkType LINK_TYPE = LinkType.SLAVE;
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		pipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, 180, TimeUnit.SECONDS));
		// 1024表示单条消息的最大长度，解码器在查找分隔符的时候，达到该长度还没找到的话会抛异常
		pipeline.addLast(new DelimiterBasedFrameDecoder(1024,//
				Unpooled.copiedBuffer(new byte[] { 0x5b }),//
				Unpooled.copiedBuffer(new byte[] { 0x5d, 0x5b }),//
				Unpooled.copiedBuffer(new byte[] { 0x5d })));
		pipeline.addLast(new MsgDecoder(this));
		pipeline.addLast(new MsgEncoder(this));
		pipeline.addLast(jt809ServerHandler);
	}

}
